import json

import requests
import os
import sys

access_token = os.getenv('JIANMU_ACCESS_TOKEN')
build_plan_id = os.getenv('JIANMU_BUILD_PLAN_ID')
api_url = os.getenv('JIANMU_API_URL')

if not api_url.endswith('/'):
    api_url = api_url + "/"

def check_param():
    if not access_token or access_token.isspace():
        print('error: 访问令牌不能为空', flush=True)
        sys.exit(1)
    if not build_plan_id or build_plan_id.isspace():
        print('error: 构建计划ID不能为空', flush=True)
        sys.exit(1)


def get_build_plan():
    headers = {
        'content-type': 'application/json',
        'authorization': access_token
    }
    url = api_url + 'auto_build_image/images/build_plans/' + build_plan_id
    response = requests.get(url=url, headers=headers)
    if 200 == response.status_code:
        return response.json()
    if 401 == response.status_code:
        print('error: 访问令牌错误或已过期，请检查更新后重试', flush=True)
        sys.exit(1)
    else:
        print('error: 获取构建计划失败, message:', response.json().get('message'), flush=True)
        sys.exit(1)


def update_build_plan(build_plan):
    headers = {
        'content-type': 'application/json',
        'authorization': access_token
    }
    url = api_url + 'auto_build_image/images/build_plans/' + build_plan_id
    response = requests.put(url=url, headers=headers, data=json.dumps(build_plan))
    if 200 == response.status_code:
        return
    if 401 == response.status_code:
        print('error: 访问令牌错误或已过期，请检查更新后重试', flush=True)
        sys.exit(1)
    else:
        print('error: 修改构建计划失败, message:', response.json().get('message'), flush=True)
        sys.exit(1)


def trigger(project_id):
    headers = {
        'content-type': 'application/json',
        'authorization': access_token
    }
    url = api_url + 'devops/projects/trigger/' + project_id
    response = requests.post(url=url, headers=headers, data=json.dumps({}))
    if 200 == response.status_code:
        return response.json()
    if 401 == response.status_code:
        print('error: 访问令牌错误或已过期，请检查更新后重试', flush=True)
        sys.exit(1)
    else:
        print('error: 触发构建计划失败, message:', response.json().get('message'), flush=True)
        sys.exit(1)


def get_workflow_instance(trigger_id):
    headers = {
        'content-type': 'application/json',
        'authorization': access_token
    }
    url = api_url + 'devops/view/workflow_instance/' + trigger_id
    response = requests.get(url=url, headers=headers)
    if 200 == response.status_code:
        return response.json()
    if 401 == response.status_code:
        print('error: 访问令牌错误或已过期，请检查更新后重试', flush=True)
        sys.exit(1)
    else:
        print('error: 获取流程实例失败, message:', response.json().get('message'), flush=True)
        sys.exit(1)